package com.leilbase.authshiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthContrller {

    @RequestMapping(value = "/login/name/{name}/password/{password}", method = RequestMethod.GET)
    public String login(@PathVariable String name, @PathVariable String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }
        return "login success";
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "logout success...Bye";
    }

    @GetMapping("/hello")
    public String hello() {
        return "Hello World";
    }

    @GetMapping("/world")
    @RequiresRoles("admin")
    public String world() {
        return "ha ha ha ...";
    }

    @GetMapping("/del")
    @RequiresPermissions({"delete", "update"})
    public String del() {
        return "delete sth";
    }

    @GetMapping("/loginPage")
    public String loginPage() {
        return "Please login first";
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "You have no auth for this page";
    }


}
